package biz

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	jsql "jujiu/data/persist/mysql"
	"log"
	"net/http"
	"strings"
	"time"
)

var cidMap map[string]string
var cidNameMap map[string]string

func init() {
	log.Println("init CIDMap ...")
	cidIpMap := make(map[string]string)
	cidIpMap["cn_real"] = "10.18.0.78"
	cidIpMap["cn_dev"] = "10.28.8.243"
	cidIpMap["eu_real"] = "172.18.2.134"
	cidIpMap["eu_dev"] = "172.28.10.172"

	cidNamMap := make(map[string]string)
	cidNamMap["cn_real"] = "Hangzhou"
	cidNamMap["cn_dev"] = "Hangzhou_dev"
	cidNamMap["eu_real"] = "Frankfurt"
	cidNamMap["eu_dev"] = "Frankfurt_dev"
	cidNameMap = cidNamMap
	cidMap = cidIpMap
	log.Println("CIDMap 初始化完成!", cidMap, cidNameMap)
}

type BizResult struct {
	Success bool   `json:"success"`
	Code    string `json:"code"`
	Msg     string `json:"msg"`
	Data    bool   `json:"data"`
}

type DispatchReq struct {
	DeviceId  int64  `json:"deviceId"`
	ClusterId string `json:"clusterId"`
}

func UpdateTcid(DeviceId int64, Sdb string, Tcid string) {
	sourceClinet, exist := jsql.DataSourceClientMap[Sdb]
	if !exist {
		log.Println("获取源数据源失败！")
	}
	info := &jsql.DeviceBaseInfo{}
	mapper := jsql.NewDeviceBaseMapper(&sourceClinet)
	info = mapper.QueryDeviceBaseInfoByDeviceId(DeviceId)
	if info == nil {
		log.Println("设备不存在！", DeviceId)
	} else {
		info.TCid = cidNameMap[Tcid]
		updateNum := mapper.UpdateDeviceBaseInfo(*info)
		if updateNum < 1 {
			log.Println("设备更新失败！", DeviceId)
		}
	}
}

func DeviceNo2DeviceId(DeviceNo string, sCid string) (int64) {
	sourceClinet, exist := jsql.DataSourceClientMap[sCid]
	if !exist {
		log.Println("获取源数据源失败！")
	}
	mapper := jsql.NewDeviceBaseMapper(&sourceClinet)
	imei := mapper.QueryByDeviceNo(DeviceNo);
	if imei == nil {
		return 0
	} else {
		return imei.DeviceId
	}
}

func Imei2DeviceId(Imei string, sCid string) (int64) {
	sourceClinet, exist := jsql.DataSourceClientMap[sCid]
	if !exist {
		log.Println("获取源数据源失败！")
	}
	mapper := jsql.NewDeviceBaseMapper(&sourceClinet)
	imei := mapper.QueryByImei(Imei);
	if imei == nil {
		return 0
	} else {
		return imei.DeviceId
	}
}

func CheckDeviceOnline(DeviceId int64, sCid string) (bool) {
	sourceClinet, exist := jsql.DataSourceClientMap[sCid]
	if !exist {
		log.Println("获取源数据源失败！")
	}
	mapper := jsql.NewDeviceBaseMapper(&sourceClinet)
	return mapper.CheckDeviceOnline(DeviceId)
}

// 获取设备的激活集群别名
func GetActiveCid(DeviceId int64, sCid string) (ActiveCid string) {
	sourceClinet, exist := jsql.DataSourceClientMap[sCid]
	if !exist {
		log.Println("获取源数据源失败！")
	}
	info := &jsql.DeviceBaseInfo{}
	mapper := jsql.NewDeviceBaseMapper(&sourceClinet)
	info = mapper.QueryDeviceBaseInfoByDeviceId(DeviceId)
	if info == nil {
		return "cn_real"
	}
	if strings.HasPrefix(info.MainRomVer, "00.000") {
		return "cn_real"
	} else if strings.HasPrefix(info.MainRomVer, "00.001") {
		return "eu_real"
	} else {
		return "cn_real"
	}
}

func Dispatch(deviceId int64, tCid string, cCid string) (*BizResult, string) {
	alias, exist := cidNameMap[tCid]
	if !exist {
		return nil, "目前集群ID不正确"
	}
	ip, ok := cidMap[cCid]
	if !ok {
		return nil, "当前集群ID不正确"
	}
	client := &http.Client{Timeout: 5 * time.Second}
	dispatchReq := &DispatchReq{}
	dispatchReq.ClusterId = alias
	dispatchReq.DeviceId = deviceId
	jsonStr, _ := json.Marshal(dispatchReq)
	req, _ := http.NewRequest("POST", "http://"+ip+":8080/bgd/conn/cluster/dispatch", bytes.NewBuffer(jsonStr))
	req.Header.Add("content-type", "application/json");
	resp, err := client.Do(req)
	if err != nil {
		log.Println(err)
		return nil, "http请求异常"
	}
	defer resp.Body.Close()

	result, _ := ioutil.ReadAll(resp.Body)
	bizResult := &BizResult{}
	unmarshal := json.Unmarshal(result, &bizResult)
	if unmarshal != nil {
		fmt.Println("error")
	}
	return bizResult, "";
}
